package com.mmx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mmx.domain.bean.FlowData;
import com.mmx.domain.entity.FlowDefinition;
import com.mmx.mapper.FlowDefinitionMapper;
import com.mmx.service.FlowDataService;
import com.mmx.service.DefinitionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @desc: 流程定义实现类
 * @author: liushuai
 * @date: 2023/1/30 15:27
 */
@Service
public class DefinitionServiceImpl implements DefinitionService {

    @Resource
    private FlowDefinitionMapper flowDefinitionMapper;
    @Resource
    private FlowDataService flowDataService;


    @Override
    public void deploy(String flowData) {
        //校验流程数据
        FlowData flowObj = flowDataService.checkFlowData(flowData);
        FlowDefinition definition = FlowDefinition.builder()
                .definitionKey(flowObj.getDefinitionKey())
                .flowData(flowData)
                .createTime(new Date())
                .build();
        synchronized (this){
            //查询最新的流程定义
            FlowDefinition flowDefinition = selectFlowDefinitionByDefinitionKey(flowObj.getDefinitionKey());
            if(flowDefinition == null){
                definition.setVersion(1);
            }else {
                definition.setVersion(flowDefinition.getVersion()+1);
            }
            flowDefinitionMapper.insertFlowDefinition(definition);
        }
    }

    @Override
    public FlowDefinition selectFlowDefinitionByDefinitionKey(String definitionKey) {
        FlowDefinition flowDefinition =  flowDefinitionMapper.selectFlowDefinitionByDefinitionKey(definitionKey);
        return flowDefinition;
    }

    @Override
    public FlowDefinition selectFlowDefinitionByInstanceId(Long instanceId) {
        if(ObjectUtil.isNull(instanceId)){
            throw new RuntimeException("流程实例ID不能为空");
        }
        FlowDefinition flowDefinition =  flowDefinitionMapper.selectFlowDefinitionByInstanceId(instanceId);
        return flowDefinition;
    }


}
